package logic

import (
	"api/internal/svc"
	"api/internal/types"
	"api/service/cert"
	"context"
	"github.com/go-pay/gopay"
	"github.com/go-pay/gopay/alipay"

	"github.com/zeromicro/go-zero/core/logx"
)

type AliLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAliLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AliLoginLogic {
	return &AliLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

//	map[alipay_cert_sn:8d3714b4df385d6ab3351b85fcc56c3a :map[access_token:authbseB2d730b90e06c4ce3bcad13dd98840X19 auth_start:2024-05-01 10:35:48 expire
//
// s_in:3.1536e+07 open_id:019rNutWc5z8EQRvGau9FJLmN4owYdK-wDgxvw-VunsCNI2 re_expires_in:3.1536e+07 refresh_token:authbseB07d6fd7c43bf4eda90b3aa3f19b15X19] sign:Oc62dngbM71OW5bWARX+UDyV
//
//	TT+hbLZit7YxzY/Yuzyti2lE6BU3H74leIZQop2LK/53wIGhMXrZ9juj2xWA1r3qjZ9vue0OwEC85BqbTiQLl5XzVtzJ6AK8426dEqmsW5rqkJa4F5Xac5DNFUqjCbWxxHNP1oAIO5hCf5eCV3wDNyGZNtKkHNBsnfuL2WH+5iIae4ojOfL3mX
//	E9WaA7RTWRs3Flp9YFn6fF3Iyow7taq7YwI5CPLHfwtGmZxvTfC7tgiY1YOwKott0vSvWoyPHGLndGhPlYaLMcZyUq8IHykrDYfybGzF8tP7u89Inmjnx8BWDraSMLXyr1GOGT8Q==]
type Response struct {
	OpenId string `json:"open_id"`
}
type AliLoginResponse struct {
	Response Response `json:"alipay_system_oauth_token_response"`
}

func (l *AliLoginLogic) AliLogin(req *types.RequestLogin) (resp *types.ResponseLogin, err error) {
	client, err := alipay.NewClient(cert.AliAPPID, cert.AliPrivateKey, true)
	if err != nil {
		l.Error("支付宝登录客户端实例失败", err)
		resp.Code = 500
		return resp, nil
	}
	//client.AutoVerifySign(cert.AliPublicRSA2) // 自动验签 老是报错
	// 模式1:代开发根据商户code获取特约服务商auth TD
	// 模式2(商户自研)
	err = client.SetCertSnByContent(cert.AliAppCer, cert.AliRootCer, cert.AliPublicCer)
	if err != nil {
		l.Error("支付宝登录自动验签失败", err)
		resp.Code = 500
		return resp, nil
	}

	bm := make(gopay.BodyMap)

	bm.Set("grant_type", "authorization_code").
		Set("code", req.Code)

	var response AliLoginResponse
	err = client.PostAliPayAPISelfV2(l.ctx, bm, "alipay.system.oauth.token", &response)
	if err != nil {
		return &types.ResponseLogin{
			OpenId: "",
			Msg:    "登录失败",
			Code:   500,
		}, nil
	} else {
		return &types.ResponseLogin{
			OpenId: response.Response.OpenId,
			Msg:    "登录成功",
			Code:   200,
		}, nil
	}
}
